package cz.zcu.fav.rat.security.service;

import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import cz.zcu.fav.rat.beans.User;
import cz.zcu.fav.rat.dataaccess.service.UserService;

public abstract class AbstractUserLoginMapper
{
	@Autowired
	private RegisteredImplementors loginImplementor;

	@Autowired
	protected UserService userService;

	@PostConstruct
	protected void init()
	{
		loginImplementor.addNewImplementor(getImplementor());
	}

	protected User getUser(String username) throws UsernameNotFoundException
	{
		List<User> users = userService.findByNicknameAndImplementor(username,
				getImplementor().getImplementor());
		if (users.isEmpty())
		{
			throw new UsernameNotFoundException(username
					+ " cannot be avaluated in " + getImplementor()
					+ " implementor");
		}

		User user = users.iterator().next();

		return user;

	}

	protected abstract LoginImplementor getImplementor();

}
